/**
 * 第五步：高级设置组件
 * 包含菜单层级、自定义需求、AI 目录结构建议
 */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Form, InputNumber, Typography, Input, Button, Card, Spin, Alert, Tree, Space } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { useDispatch, useSelector } from 'react-redux';
import { FormInstance } from 'antd';
import { AppDispatch } from '@/store';
import { RootState, ProjectDirectoryNode } from '@/types';
import { generateDirectoryStructure } from '@/store/slices/projectSlice';
import styles from './AdvancedSettingsStep.module.css';

const { TextArea } = Input;
const { Text, Title } = Typography;

interface AdvancedSettingsStepProps {
  form: FormInstance;
}

const normalizeComponentList = (value: any): string[] => {
  if (!Array.isArray(value)) return [];
  return value
    .map((item) => {
      if (typeof item === 'string') return item;
      if (item && typeof item === 'object') {
        return item.name || item.label || '';
      }
      return '';
    })
    .filter(Boolean);
};

const buildTreeData = (nodes: ProjectDirectoryNode[], parentKey = 'root'): DataNode[] =>
  nodes.map((node, index) => {
    const key = `${parentKey}-${index}`;
    const children: DataNode[] = [];

    if (node.files?.length) {
      node.files.forEach((fileName, fileIndex) => {
        children.push({
          key: `${key}-file-${fileIndex}`,
          title: (
            <span className={styles.treeFile}>
              {fileName}
            </span>
          ),
          isLeaf: true,
        });
      });
    }

    if (node.children?.length) {
      children.push(...buildTreeData(node.children, key));
    }

    return {
      key,
      title: (
        <div className={styles.treeNodeTitle}>
          <span className={styles.treeNodeName}>{node.name}</span>
          {node.description && (
            <span className={styles.treeNodeDesc}>{node.description}</span>
          )}
        </div>
      ),
      children,
    } as DataNode;
  });

const AdvancedSettingsStep: React.FC<AdvancedSettingsStepProps> = ({ form }) => {
  const dispatch = useDispatch<AppDispatch>();
  const {
    directoryStructure,
    directorySummary,
    structureLoading,
    structureError,
  } = useSelector((state: RootState) => state.project);

  const [autoRequested, setAutoRequested] = useState(false);

  const baseComponents = normalizeComponentList(Form.useWatch('baseComponents', form));
  const extendedComponents = normalizeComponentList(Form.useWatch('extendedComponents', form));
  const uiFramework = Form.useWatch('uiFramework', form) || 'react';
  const language = Form.useWatch('language', form) || 'typescript';
  const buildTool = Form.useWatch('buildTool', form) || 'vite';
  const targetPlatform = Form.useWatch('targetPlatform', form) || 'web';
  const requirementDescription = Form.useWatch('requirementDescription', form) || '';

  const treeData = useMemo<DataNode[]>(
    () => buildTreeData(directoryStructure),
    [directoryStructure]
  );

  const componentKey = useMemo(
    () =>
      JSON.stringify({
        baseComponents,
        extendedComponents,
        uiFramework,
        language,
        buildTool,
        targetPlatform,
        requirementDescription,
      }),
    [
      baseComponents,
      extendedComponents,
      uiFramework,
      language,
      buildTool,
      targetPlatform,
      requirementDescription,
    ]
  );

  const handleGenerateStructure = useCallback(() => {
    const formValues = form.getFieldsValue();
    dispatch(
      generateDirectoryStructure({
        projectName: formValues.projectName,
        description: formValues.requirementDescription,
        uiFramework: formValues.uiFramework,
        language: formValues.language,
        buildTool: formValues.buildTool,
        targetPlatform: formValues.targetPlatform,
        baseComponents: normalizeComponentList(formValues.baseComponents),
        extendedComponents: normalizeComponentList(formValues.extendedComponents),
      })
    );
  }, [dispatch, form]);

  useEffect(() => {
    if (!autoRequested && (baseComponents.length || extendedComponents.length)) {
      handleGenerateStructure();
      setAutoRequested(true);
    }
  }, [autoRequested, baseComponents.length, extendedComponents.length, handleGenerateStructure]);

  useEffect(() => {
    if (autoRequested) {
      setAutoRequested(false);
    }
  }, [componentKey]);

  return (
    <Space direction="vertical" size={24} style={{ width: '100%' }}>
      <Form.Item
        name="maxLevels"
        label="最大菜单层级"
        rules={[
          { required: true, message: '请输入最大菜单层级' },
          { type: 'number', min: 1, max: 10, message: '最大层级必须在1-10之间' }
        ]}
        extra={<Text type="secondary" className="text-xs">设置菜单层级的最大深度，推荐2-4层</Text>}
      >
        <InputNumber 
          min={1} 
          max={10} 
          placeholder="用于自动生成侧边栏菜单" 
          style={{ width: '100%' }}
        />
      </Form.Item>
      
      <Form.Item
        name="customRequirements"
        label="自定义需求"
        extra="描述您的特殊需求，我们会尽量在生成的项目中体现"
      >
        <TextArea 
          placeholder="例如：需要集成特定的认证方式、需要生成 Dockerfile、需要特定的目录结构等" 
          rows={6}
          maxLength={1000}
          showCount
        />
      </Form.Item>

      <Card className={styles.structureCard} title={<Title level={5}>项目目录结构建议</Title>}>
        <div className={styles.structureHeader}>
          <Text type="secondary">
            根据当前的技术栈与组件选择，AI 将生成可落地的目录结构建议。
          </Text>
          <Button type="primary" onClick={handleGenerateStructure} loading={structureLoading}>
            生成目录结构
          </Button>
        </div>

        {structureError && (
          <Alert
            type="error"
            message="目录结构生成失败"
            description={structureError}
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        <Spin spinning={structureLoading} tip="AI 正在分析目录结构...">
          {directorySummary && (
            <Alert
              type="info"
              message="分析摘要"
              description={directorySummary}
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}

          {treeData.length > 0 ? (
            <div className={styles.treeContainer}>
              <Tree
                treeData={treeData}
                defaultExpandAll
                selectable={false}
                showLine
              />
            </div>
          ) : (
            <div className={styles.emptyStructure}>
              <Text type="secondary">点击“重新生成”获取目录结构建议。</Text>
            </div>
          )}
        </Spin>
      </Card>

      <div className="bg-blue-50 p-4 rounded-lg">
        <Text type="secondary" className="text-sm">
          💡 提示：完成配置后，我们将根据您的选择生成包含完整项目结构、依赖配置和基础组件的项目模板。
        </Text>
      </div>
    </Space>
  );
};

export default AdvancedSettingsStep;
